package com.example.managemyself.ui.diary;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.viewmodel.DiaryViewModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * 日记列表Fragment，显示所有日记条目
 */
public class DiaryListFragment extends Fragment {

    private DiaryViewModel viewModel;
    private RecyclerView recyclerView;
    private DiaryAdapter adapter;
    private TextView tvEmptyView;
    private SearchView searchView;
    private FloatingActionButton fabAddDiary;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_diary_list, container, false);
        
        // 初始化视图
        recyclerView = root.findViewById(R.id.recyclerViewDiary);
        tvEmptyView = root.findViewById(R.id.tvEmptyView);
        searchView = root.findViewById(R.id.searchView);
        fabAddDiary = root.findViewById(R.id.fabAddDiary);
        
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        try {
            // 初始化ViewModel
            viewModel = new ViewModelProvider(requireActivity()).get(DiaryViewModel.class);
            
            // 设置RecyclerView
            setupRecyclerView();
            
            // 设置搜索功能
            setupSearchView();
            
            // 设置添加按钮点击事件
            fabAddDiary.setOnClickListener(v -> navigateToDiaryFragment());
            
            // 观察日记数据变化
            observeDiaryEntries();
        } catch (Exception e) {
            Toast.makeText(requireContext(), "日记页面初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 设置RecyclerView
     */
    private void setupRecyclerView() {
        adapter = new DiaryAdapter(new ArrayList<>(), this::onDiaryItemClick);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.setAdapter(adapter);
    }
    
    /**
     * 设置搜索功能
     */
    private void setupSearchView() {
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchDiaries(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    // 如果搜索框为空，显示所有日记
                    observeDiaryEntries();
                }
                return false;
            }
        });
    }
    
    /**
     * 观察日记数据变化
     */
    private void observeDiaryEntries() {
        viewModel.getAllDiaryEntries().observe(getViewLifecycleOwner(), diaryEntries -> {
            if (diaryEntries != null && !diaryEntries.isEmpty()) {
                adapter.updateData(diaryEntries);
                tvEmptyView.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            } else {
                tvEmptyView.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        });
    }
    
    /**
     * 搜索日记
     */
    private void searchDiaries(String keyword) {
        if (keyword.isEmpty()) {
            observeDiaryEntries();
            return;
        }
        
        viewModel.searchDiaryEntries(keyword).observe(getViewLifecycleOwner(), diaryEntries -> {
            if (diaryEntries != null && !diaryEntries.isEmpty()) {
                adapter.updateData(diaryEntries);
                tvEmptyView.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            } else {
                adapter.updateData(new ArrayList<>());
                tvEmptyView.setText("未找到匹配的日记");
                tvEmptyView.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        });
    }
    
    /**
     * 日记项点击事件
     */
    private void onDiaryItemClick(DiaryEntry diaryEntry) {
        // 设置选中的日记
        viewModel.selectDiaryEntry(diaryEntry);
        
        // 跳转到日记详情页面
        Intent intent = new Intent(requireContext(), DiaryDetailActivity.class);
        intent.putExtra(DiaryDetailActivity.EXTRA_DIARY_ID, diaryEntry.getId());
        startActivity(intent);
    }
    
    /**
     * 导航到日记编辑页面
     */
    private void navigateToDiaryFragment() {
        Navigation.findNavController(requireView()).navigate(R.id.action_diaryListFragment_to_diaryFragment);
    }
    
    /**
     * 日记适配器
     */
    private static class DiaryAdapter extends RecyclerView.Adapter<DiaryAdapter.DiaryViewHolder> {
        
        private List<DiaryEntry> diaryEntries;
        private final OnDiaryItemClickListener listener;
        
        public DiaryAdapter(List<DiaryEntry> diaryEntries, OnDiaryItemClickListener listener) {
            this.diaryEntries = diaryEntries;
            this.listener = listener;
        }
        
        public void updateData(List<DiaryEntry> newDiaryEntries) {
            this.diaryEntries = newDiaryEntries;
            notifyDataSetChanged();
        }
        
        @NonNull
        @Override
        public DiaryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_diary, parent, false);
            return new DiaryViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull DiaryViewHolder holder, int position) {
            DiaryEntry diaryEntry = diaryEntries.get(position);
            holder.bind(diaryEntry, listener);
        }
        
        @Override
        public int getItemCount() {
            return diaryEntries.size();
        }
        
        static class DiaryViewHolder extends RecyclerView.ViewHolder {
            private final TextView tvTitle;
            private final TextView tvDate;
            private final TextView tvMood;
            private final TextView tvWeather;
            private final TextView tvContent;
            private final View ivImage;
            
            public DiaryViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvDiaryTitle);
                tvDate = itemView.findViewById(R.id.tvDiaryDate);
                tvMood = itemView.findViewById(R.id.tvMood);
                tvWeather = itemView.findViewById(R.id.tvWeather);
                tvContent = itemView.findViewById(R.id.tvDiaryContent);
                ivImage = itemView.findViewById(R.id.ivDiaryImage);
            }
            
            public void bind(DiaryEntry diaryEntry, OnDiaryItemClickListener listener) {
                tvTitle.setText(diaryEntry.getTitle());
                
                // 格式化日期
                java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy年MM月dd日", java.util.Locale.getDefault());
                tvDate.setText(dateFormat.format(diaryEntry.getDate()));
                
                // 设置心情和天气
                if (diaryEntry.getMood() != null && !diaryEntry.getMood().isEmpty()) {
                    tvMood.setText("心情: " + diaryEntry.getMood());
                    tvMood.setVisibility(View.VISIBLE);
                } else {
                    tvMood.setVisibility(View.GONE);
                }
                
                if (diaryEntry.getWeather() != null && !diaryEntry.getWeather().isEmpty()) {
                    tvWeather.setText("天气: " + diaryEntry.getWeather());
                    tvWeather.setVisibility(View.VISIBLE);
                } else {
                    tvWeather.setVisibility(View.GONE);
                }
                
                // 设置内容
                tvContent.setText(diaryEntry.getContent());
                
                // 设置图片
                if (diaryEntry.getImageUri() != null && !diaryEntry.getImageUri().isEmpty()) {
                    ivImage.setVisibility(View.VISIBLE);
                    // TODO: 加载图片
                } else {
                    ivImage.setVisibility(View.GONE);
                }
                
                // 设置点击事件
                itemView.setOnClickListener(v -> listener.onDiaryItemClick(diaryEntry));
            }
        }
        
        interface OnDiaryItemClickListener {
            void onDiaryItemClick(DiaryEntry diaryEntry);
        }
    }
} 